package servlet.User;

import DAO.UserDAO;
import Model.User;
import appexception.AppException;
import com.fasterxml.jackson.databind.ObjectMapper;
import service.BaseService;
import unit.JSONResponse;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @program: wsn_blog
 * @description
 * @author:王松年
 * @creat: 2021-07-12 14:48:09
 **/

@WebServlet("/login")
public class UserLoginServlet extends BaseService{
    @Override
    protected void query(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        User loginUser = objectMapper.readValue(req.getInputStream(), User.class);
        //判断用户名或密码是否为空
        if (loginUser.getUsername()==null||loginUser.getUsername().length()==0){
            throw new AppException("LOGIN001","请输入用户名");
        }
        if (loginUser.getPassword()==null||loginUser.getPassword().length()==0){
            throw new AppException("LOGIN002","请输入密码");
        }
        //查询用户是否存在
        User user = UserDAO.selectByUser(loginUser);
        if (user==null){//用户不存在
            throw new AppException("LOGIN003","用户不存在，请检查用户名是否正确！");
        }
        if (!user.getPassword().equals(loginUser.getPassword()) ){//用户存在，但密码不正确
            throw new AppException("LOGIN004","用户名或密码错误！");
        }
        //用户名和密码都正确
        //设置session
        HttpSession session = req.getSession(true);
        //把用户信息放入session供后边使用
        session.setAttribute("user",user);
        //设置响应信息
        json.setData(user);
    }
}